import axios, { AxiosResponse } from 'axios';
import { notification } from 'antd';
import { delUserStorage, storage } from './tools'
import { saveAs } from 'file-saver';
export const CancelSource: any = {
  source: {
    token: undefined,
    cancel: null,
  },
};

export const interceptErrorConfig: { interceptCodes: number[] } = { interceptCodes: [] };

export const cancelRequest = () => {
  CancelSource.source?.cancel && CancelSource.source?.cancel();
  const CancelToken = axios.CancelToken;
  CancelSource.source = CancelToken.source();
};

const checkLogin = (resp: AxiosResponse) => {
  const code = resp.data.code;
  if (!resp.data.type && code === 401) {
    localStorage.clear()
    setTimeout(function () {
    //如果对接中台，就返回中台那里
     if(localStorage.getItem("cloudjsToken")){
        const env = import.meta.env.VITE_APP_ENV
        if(env==='test'||env==='dev'){
           window.location.href = 'https://admin-uat.028wlkj.com:1020/login';
        }else {
           window.location.href = 'https://admin.028wlkj.com:1020/login';
        }
      }else{
        window.location.href = '/login';
      }  
    }, 800);
  }
};

axios.defaults.baseURL = import.meta.env.VITE_BASE_API
axios.interceptors.request.use(function (config: any) {
  if (config.headers.type === "menu") {
    config.baseURL = import.meta.env.VITE_MENU_API
  }
  let token = localStorage.getItem('token')
  config.headers.token = token
  config.headers.Authorization = token
  if(localStorage.getItem("cloudjsToken")){
    let cloudjsToken = localStorage.getItem("cloudjsToken")
    let tokenWithoutBearer = cloudjsToken.replace('Bearer ', '');
    config.headers.token = tokenWithoutBearer
    config.headers.Authorization = tokenWithoutBearer
  }
  // config.headers['Content-Type'] = 'application/json';
  config.timeout === null ? (config.timeout = null) : (config.timeout = 300000);

  // custom error
  config.interceptCodes = interceptErrorConfig.interceptCodes;
  //  add source cancel
  config.cancelToken = config.cancelToken ? config.cancelToken : CancelSource.source.token;
  return config;
});

axios.interceptors.response.use(
  function (response: any) {
    checkLogin(response);
    // Uniformly handles errors returned by the server
    const { data, config  } = response;
    if (data && data.code !== 200 && data.msg && !config.interceptCodes.includes(data.code)) {
      notification.error({ message: response.data.msg });
    }
    return response;
  },
  function (error) {
    if (!axios.isCancel(error)) {
      console.log('request error:', error.message);
      const msg = error.response.data?.msg
      const message = msg || (error && error.message ? error.message : 'Unknown error, please check your network ~');
      notification.error({ message });
    }
    return error;
  }
);

export const post = (url: string, param?: any, headers?: any, timeout?: any, cancel?: any): Promise<any> => {
  return axios
    .post(url, param, {
      headers: headers || {},
      timeout: timeout,
      cancelToken: cancel,
    })
    .then((resp) => {
      return resp?.data ? resp?.data : { data: null, code: -1 };
    });
};

export const put = (url: string, param: any) => {
  return axios.put(url, param).then((resp) => resp.data);
};

export const get = (url: string, params?: any, headers?: any): Promise<any> => {
  return axios.get(url, { params, headers: headers || {} }).then((resp) => {
    return resp?.data ? resp?.data : { data: null, code: -1 };
  });
};

export const del = (url: string, params: any) => {
  return axios.delete(url, { params }).then((resp) => resp.data);
};

export const fileDownload = (url: string, params: any, fileName: string, method?: 'post' | 'get') => {
  return axios({
    method: method ? method : 'post',
    url: url,
    data: params,
    headers: {
      'Content-Type': 'application/json;application/octet-stream',
    },
    responseType: 'blob',
  }).then((res) => {
    const content = res.data;
    if (!content) {
      return false;
    }
    const blob = new Blob([content]);
    saveAs(blob, fileName)
    return true
  });
};

export const downloadFile = (url: string) => {
  window.open(url);
};
